﻿using famails.bus;
using famails.common;
using famails.dto;
using FAMailUtils.MailGun;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Net.Mail;
using System.Web;
using System.Web.Script.Services;
using System.Web.Services;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace famails.BackEnd.page
{
    public partial class Client : System.Web.UI.Page
    {
        static log4net.ILog logs = log4net.LogManager.GetLogger("ErrorRollingLogFileAppender");
        static log4net.ILog logs_info = log4net.LogManager.GetLogger("InfoRollingLogFileAppender");

        static UserLoginDTO userLogin = null;
        protected void Page_Load(object sender, EventArgs e)
        {
            userLogin = getUserLogin();
            if (!IsPostBack)
            {
                //txtFromDate.Text = DateTime.Now.ToString("dd/MM/yyyy");
                //txtToDate.Text = DateTime.Now.ToString("dd/MM/yyyy");
            }
        }
        public UserLoginDTO getUserLogin()
        {
            if (Session["us-login"] != null)
            {
                return (UserLoginDTO)Session["us-login"];
            }
            else Response.Redirect("~/backend/page/login.aspx?rUrl=" + Request.Url.PathAndQuery);
            return null;
        }
        [WebMethod]
        public static void Delete(int clientid)
        {
            try
            {
                ClientBUS clientBUS = new ClientBUS();
                bool result = clientBUS.Delete(clientid);
                if (result)
                    logs_info.Error(userLogin.Username + "- Client - Delete clientid:" + clientid);
                else throw new Exception("Tài khoản này đã phát sinh gửi email. Bạn không được phép xóa!");
            }
            catch (Exception ex)
            {
                logs.Error(userLogin.Username + "- Client - Delete", ex);
                throw ex;
            }
        }
        [WebMethod]
        public static void Active(int clientid, string email)
        {
            try
            {
                ClientBUS clientBUS = new ClientBUS();
                DataTable data = clientBUS.getallclient(clientid);
                clientBUS.Customer_Active(clientid);

                logs_info.Info(userLogin.Username + "- Client - Active clientid:" + clientid + " email:" + email);
                if (data.Rows.Count > 0)
                {
                    //string from = ConfigurationManager.AppSettings["SystemRegisterEmail"].ToString();
                    //string to = data.Rows[0]["email"] + "";
                    //string Subject = "Thư xác nhận";
                    //string Body = "<html>  <body><table class='auto-style1'> <tr><td>Chào " + data.Rows[0]["clientName"] + " Thân mến! </td></tr><tr><td>Tài khoản của quý khách đã được kích hoạt thành công. </td></tr><tr><td>Thông tin tài khoản đăng nhập</td></tr><tr><td> Email đăng nhập: '" + data.Rows[0]["email"] + "'</td></tr><tr><td>Click vào <a href='http://famails.com/backend/page/login.aspx'>đây để đăng nhập vào hệ thống famails</a> </td></tr><tr> <td> Trân trọng, </td</tr> <tr> <td>Hệ thống FAMails.com </td</tr><tr><td> Email:support@famails.com</td></tr></table></body>  ";
                    //Body += "</html>";
                    //SendMail sendmail = new SendMail(ConfigurationManager.AppSettings["api-key"]);
                    //SendResult result = sendmail.SendHtmlMessage(from.Split('@')[1] + "", "Hệ thống FAMails.com", from, to, Subject, Body, false);


                    Common.SendMailActiveSuccess(clientid);
                }
            }
            catch (Exception ex)
            {
                logs.Error(userLogin.Username + "- Client - Active", ex);
                throw ex;
            }
        }
        [WebMethod]
        public static void UnLock(int clientid, string action)
        {
            try
            {
                ClientBUS clientBUS = new ClientBUS();
                if (action == "Lock")
                    clientBUS.Customer_Lock_Unlock(clientid, Common.clientStatus.Lock);
                else
                    clientBUS.Customer_Lock_Unlock(clientid, Common.clientStatus.Normal);

                logs_info.Error(userLogin.Username + "- Client - UnLock clientid:" + clientid + " action:" + action);
            }
            catch (Exception ex)
            {
                logs.Error(userLogin.Username + "- Client - UnLock" + action, ex);
                throw ex;
            }
        }

        [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public static List<ClientResult> Search(string name, string phone, string email, string from, string to)
        {
            userLogin = (UserLoginDTO)HttpContext.Current.Session["us-login"];
            ClientBUS clientBUS = new ClientBUS();
            DataTable customerBySelect = clientBUS.Search(name, email, phone, false, from, to);
            List<ClientResult> result = new List<ClientResult>();
            ClientResult item = new ClientResult();
            foreach (DataRow dr in customerBySelect.Rows)
            {
                item = new ClientResult();
                item.Clientid = Convert.ToInt32(dr["clientid"] + "");
                item.clientName = dr["clientName"] + "";
                item.Email = dr["Email"] + "";
                item.Phone = dr["Phone"] + "";
                item.action = dr["action"] + "";
                item.PackageName = dr["PackageName"] + "";
                if (dr["activeDate"]+""!="")
                item.ActiveDate = Convert.ToDateTime(dr["activeDate"] + "");
                if (dr["ExpireDate"] + "" != "")
                item.ExpireDate = Convert.ToDateTime(dr["ExpireDate"] + "");
                decimal temp = 0;Decimal.TryParse(dr["Limit"] + "", out temp);
                item.Limit = temp;
                temp = 0; Decimal.TryParse(dr["EmailCount"] + "", out temp);
                item.EmailCount = temp;
                item.Sstatus = dr["Sstatus"] + "";
                result.Add(item);
            }

            return result;
        }
    }
    public class ClientResult
    {
        public int Clientid { get; set; }
        public string clientName { get; set; }
        public string Email { get; set; }
        public string Phone { get; set; }
        public string PackageName { get; set; }
        public DateTime ActiveDate { get; set; }
        public DateTime ExpireDate { get; set; }
        public decimal Limit { get; set; }
        public decimal EmailCount { get; set; }
        public string Sstatus { get; set; }
        public string action { get; set; }
    }

}